<template>
  <div class="yy-schedule-selector" @click.stop>
    <el-dialog
        v-model="isVisible"
        title="患者查询"
        draggable
        width="800px"
        :close-on-click-modal="false"
        @close="onCancelDialog"
        :show-close="true"
        class="yy-modal--custom"
    >
      <div class="yy-schedule-selector_list" v-if="!isLoading && queues?.length">
        <div class="yy-schedule-selector_list-item" :key="item.queue.id" v-for="item in queues">
          <div>
            <label>患者姓名:</label>
            <span>{{item.queue.patientName}}</span>
          </div>
          <div>
            <label>就诊序号:</label>
            <span>{{item.queue.registerNo}}</span>
          </div>
          <div>
            <label>挂号时间:</label>
            <span>{{formatDate(item.queue.registerTime)}}</span>
          </div>
          <div>
            <label>科室名称:</label>
            <span>{{item.queue.departName}}</span>
          </div>
          <div>
            <label>挂号科目:</label>
            <span>{{item.queue.itemName}}</span>
          </div>
          <div v-if="item.queue.doctorId">
            <label>签到医生:</label>
            <span>{{item.queue.doctorName}}</span>
          </div>
          <div v-if="item.queue.scheduleFlag === 1">
            <label>预约时间:</label>
            <span>{{item.queue.scheduleFromTime + '-' + item.queue.scheduleToTime}}</span>
          </div>
          <div>
            <label>等待人数:</label>
            <span>{{item.await}}</span>
          </div>
          <div>
            <el-button style="min-width: 200px" type="primary" v-if="item.queue.registerFlag === 1 " :disabled="!canSignState(item.queue) || isSinging" @click.stop="onSignPatient(item)">
              {{item.queue.state === 3 ? '过号重签': canSignState(item.queue) ? '签到' : '已签到'}}
            </el-button>
            <el-button style="min-width: 200px" type="info" v-if="item.queue.registerFlag === 0 " :disabled="true">
              {{'已退号'}}
            </el-button>
          </div>
        </div>
      </div>
      <div style="padding: 20px; text-align: center;" v-if="errorMsg">{{errorMsg}}</div>
      <div style="text-align: center; padding: 50px 0;" v-if="!errorMsg && !isLoading && (!queues || queues.length == 0)"> 未查询到卡号[{{selectCardNo}}]在当前科室的挂号信息 </div>
      <div style="text-align: center; padding: 50px 0;" v-if="isLoading"> 正在查询挂号信息，请稍后... </div>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import {ref,defineExpose,computed } from "vue";
import {QueueItemModel} from "@/model/QueueItemModel";
import {findMaxRepeatedSubstring, formatDate} from "../../utils/yayi";
import CardApi from "@/api/card"

const $emit = defineEmits({
  rebackCardNo: (cardNo) => cardNo,
  cancelSearchCardNoDialog: () => true
})

const isVisible = ref(false)

const canSignState = computed(() => {
  return (queue) => {
    return (!queue.state || (queue.state === 2 && queue.visitState >= 2) || queue.state === 3 || queue.state === 5)
  }
})

const queues = ref<{await: number, queue: QueueItemModel}[]>([])
const selectCardNo = ref()
const isLoading = ref(true)
const selectDepartId = ref()
const selectItemId = ref()
const isSinging = ref(false)
const errorMsg = ref("")

const onShowDialog = (departId, itemId, inputCardNo) => {
  selectCardNo.value = inputCardNo
  selectDepartId.value = departId
  selectItemId.value = itemId
  isVisible.value = true
  searchPatientByCardNo()
}

const filterCurrentDepart = (data: {await: number, queue: QueueItemModel}[]) => {
  return data.filter(item => item.queue.departId === selectDepartId.value && item.queue.itemId === selectItemId.value)
}

const searchPatientByCardNo = () => {
  isLoading.value = true
  // 刷卡识别后执行查询
  if (selectCardNo.value) {
    const cardNo = selectCardNo.value
    console.log("读取到未去重的签到卡号:" + cardNo)
    CardApi.searchPatientWithCardNo(findMaxRepeatedSubstring(cardNo)).then((data) => {
      console.log("-----------------", data)
      queues.value = filterCurrentDepart(data)
      isLoading.value = false
    }, (msg) => {
      isLoading.value = false
    })
  } else {
    // 插卡读取
    CardApi.huaxuRead().then((cardNo) => {
      console.log("--------cardNo---------", cardNo)
      selectCardNo.value = cardNo
      $emit('rebackCardNo', cardNo)
      if (cardNo) {
        CardApi.searchPatientByCardNo(cardNo).then((data) => {
          console.log("-----------------", data)
          queues.value = filterCurrentDepart(data)
          isLoading.value = false
        }, () => {
          console.log("读取卡号["+cardNo+"]查询信息失败，重新模糊匹配查询")
          CardApi.searchPatientByCardNo(cardNo, 1).then((data) => {
            console.log("卡号["+cardNo+"]模糊匹配查询成功", data)
            queues.value = filterCurrentDepart(data)
            isLoading.value = false
          }, (msg) => {
            console.log("卡号["+cardNo+"]模糊匹配查询失败", msg)
            isLoading.value = false
          })
        })
      }
    }, (msg) => {
      console.log("---------卡号读取失败--------", msg)
      isLoading.value = false
      errorMsg.value = '读卡失败，未查询到卡号信息'
    })
  }
}

const onSignPatient = function (patient) {
  if (isSinging.value || !(!patient.queue.state || (patient.queue.state === 2 && patient.queue.visitState > 2) || patient.queue.state === 3 || patient.queue.state === 5)) {
    return
  }
  errorMsg.value = ''
  isSinging.value = true
  CardApi.signByCardNo(patient.queue.id).then((data) => {
    errorMsg.value = "签到成功，请等候叫号再就诊！"
    patient.await = data.await
    patient.queue = Object.assign({}, patient.queue, data.queue)
    patient.doctor = Object.assign({}, patient.doctor||{}, data.doctor || {})
    isSinging.value = false
  }, () => {
    errorMsg.value = patient.queue.departName+ "签到失败，请重试！"
    isSinging.value = false
  })
}

const onCancelDialog = () => {
  isVisible.value = false
  queues.value = []
  errorMsg.value=  ''
  selectCardNo.value = ''
  selectDepartId.value = ''
  selectItemId.value = ''
  $emit('cancelSearchCardNoDialog')
}

defineExpose({
  onShowDialog
})

</script>
<style scoped lang="scss">
  .yy-schedule-selector_list {
    padding: 10px 0;
    line-height: 32px;
    letter-spacing: 2px;
    font-size: 18px;
    text-align: center;
    &-item {
      display: inline-block;
      border: 1px solid #1d90fd;
      padding: 15px;
      margin: 10px;
      & > div {
        text-align: left;
        & > label {
          display: inline-block;
          width: 100px;
        }
        & > span {
          flex: 1;
        }
      }
      & > div:last-child {
        margin-top: 10px;
        padding-top: 10px;
        border-top: 1px solid #d1d1d1;
        text-align: center;
      }
    }
    label {
      font-weight: normal;
    }
    span {
      margin-left: 5px;
      font-weight: 700;
    }
  }
</style>
